import {
  trademarkItemType,
  trademarkListType,
} from "@/api/product/model/trademarkType";
import {
  reqAddTrademark,
  reqDeleteTrademark,
  reqTrademarkList,
  reqUpdataTrademark,
} from "@/api/product/trademark";
import {
  CheckOutlined,
  DeleteOutlined,
  EditOutlined,
  LoadingOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import { Button, Card, Form, Input, message, Modal, Table, Upload } from "antd";
import { useForm } from "antd/lib/form/Form";
import { ColumnsType } from "antd/lib/table/Table";
import { RcFile, UploadChangeParam, UploadProps } from "antd/lib/upload";
import { UploadFile } from "antd/lib/upload/interface";
import React, { useEffect, useState } from "react";

export default function Trademark() {
  //1. 定义数据
  const [trademarkList, setTrademarkList] = useState<trademarkListType>([]);
  // 2.是否在加载
  const [loading, setLoading] = useState(false);
  //3.定义当当前页码
  const [current, setCurrent] = useState(1);
  //4. 定义当前条数
  const [pageSize, setPageSize] = useState(5);
  //5. 定义当前总数
  const [total, setTotal] = useState(100);
  //6.定义图片
  const [logoUrl, setLogoUrl] = useState("");
  // 7.当前的列
  const columns: ColumnsType<trademarkItemType> = [
    {
      title: "序号",
      width: 100,
      render(value, record, index) {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      width: 100,
      dataIndex: "tmName",
    },
    {
      title: "品牌Logo",
      width: 100,
      dataIndex: "logoUrl",

      render(value, record, index) {
        return <img src={value} alt="logo" width={80} />;
      },
    },
    {
      title: "操作",
      width: 100,
      render(row: trademarkItemType) {
        return (
          <>
            <Button
              type="primary"
              style={{ margin: "0 10px" }}
              onClick={() => {
                showAddModel(row);
              }}
            >
              <EditOutlined />
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => {
                deleteTrademark(row.id);
              }}
            >
              <DeleteOutlined />
            </Button>
          </>
        );
      },
    },
  ];
  //8. 定义对话框是否显示
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 9.定义图片的地址
  const BASE_URL = `http://gmall-h5-api.atguigu.cn`;
  // 10.定义id
  const [id, setId] = useState(NaN);
  //11. form的数据
  const [form] = useForm();
  // 12.定义品牌名
  const [tmName, setTmName] = useState("");

  // 图片上传前的钩子
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };
  // 上传中、完成、失败都会调用这个函数
  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      setLoading(false);
      // console.log(info.file.response.data,'123');
      setLogoUrl(info.file.response.data);
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  // 初识品牌数据
  useEffect(() => {
    getTrademarkList();
  }, []);

  //1.请求品牌分页
  const getTrademarkList = async (
    page: number = current,
    limit: number = pageSize
  ) => {
    // 打开loading
    setLoading(true);
    const re = await reqTrademarkList(page, limit);
    // console.log(re);
    setTrademarkList(re.records);
    setCurrent(re.current);
    setPageSize(re.size);
    setTotal(re.total);
    // 关闭loading
    setLoading(false);
  };

  // 2.点击添加按钮的事件
  const showAddModel = (row?: trademarkItemType) => {
    setIsModalOpen(true);
    // console.log("打开");
    setId(-1);
    if (row?.id) {
      // 有就是修改 在这里回填数据
      form.setFieldsValue({
        tmName: row.tmName,
        // logoUrl: row.logoUrl,
      });
      setLogoUrl(row.logoUrl);
      setId(row.id);
    } else {
      // 添加品牌 清空表单
      form.setFieldsValue({
        tmName: "",
      });
      setLogoUrl("");
    }
  };

  // 3.添加确定 新增一个品牌 或是修改的一个品牌的请求
  const submitOnchange = async (values: any) => {
    // 打开loading
    setLoading(true);
    if (id === -1) {
      // console.log(e);
      setTmName(values.tmName);
      await reqAddTrademark(values.tmName, logoUrl);
      message.success("新增成功");
      // 清空表单 ?
    } else {
      // 修改
      // 整理参数
      const tmInfo = {
        id,
        tmName: values.tmName,
        logoUrl,
      };
      // 发送修改请求.
      await reqUpdataTrademark(tmInfo);
      message.success("修改成功");
    }
    // 关闭弹窗
    setIsModalOpen(false);
    // 关闭loading
    setLoading(false);
    // 重新发送请求
    getTrademarkList();
  };

  //4. 点击取消或者X关闭弹窗的事件
  const handleCanle = () => {
    setIsModalOpen(false);
  };
  // 5.修改一个品牌的事件

  //5.删除一个品牌
  const deleteTrademark = async (id: number) => {
    await reqDeleteTrademark(id);
    message.success("删除成功");
    // 重新发送请求
    getTrademarkList();
  };

  return (
    <>
      <Card>
        <Button
          type="primary"
          onClick={() => {
            showAddModel();
          }}
        >
          <PlusOutlined />
          添加
        </Button>
        <Table
          bordered
          loading={loading}
          dataSource={trademarkList}
          columns={columns}
          rowKey="id"
          pagination={{
            current,
            pageSize,
            total,
            showTotal: (total) => `共${total}条`,
            showSizeChanger: true,
            // 是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
            showQuickJumper: true,
            // 是否可以快速跳转至某页
            onChange: getTrademarkList,
            // 页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
          }}
        ></Table>
      </Card>

      {/* 添加或修改品牌的弹窗 */}
      <Modal
        title="添加品牌"
        visible={isModalOpen}
        onCancel={handleCanle}
        footer={null}
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          autoComplete="off"
          onFinish={submitOnchange}
        >
          <Form.Item
            label="品牌名称"
            name="tmName"
            rules={[{ required: true, message: "必须要输入用户名!" }]}
          >
            <Input placeholder="请输入品牌名称" />
          </Form.Item>

          <Form.Item label="品牌Logo" >
            {/* 图片上传 */}
            <Upload
              listType="picture-card"
              showUploadList={false}
              action={`${BASE_URL}/admin/product/fileUpload`}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {logoUrl ? (
                <img src={logoUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item style={{ float: "right", marginTop: -30 }}>
            <Button type="primary" htmlType="submit" icon={<CheckOutlined />}>
              确定
            </Button>
            <Button className="ml" onClick={handleCanle}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
